package griffin.website;

//import griffin.website.contentlist.ItemClickListener;
import CIT.Test.GalleryFlow;
import android.content.pm.ActivityInfo;
import griffin.website.Login.TouchItemClickListener;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.os.Bundle;
import android.text.Editable;
import android.text.Html;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.AutoCompleteTextView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.RatingBar;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.view.View.OnTouchListener;
import android.view.inputmethod.InputMethodManager;
import android.view.View.OnTouchListener;
import android.view.MotionEvent;
import android.content.Context;
import android.util.*;
import java.util.regex.*;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.AbsListView.OnScrollListener;

public class SearchSite extends Activity {
	private View view ;
	AutoCompleteTextView tvKeyword;
	private static final String TAG = "[SearchSite]";
	private List<Map<String, Object>> resultList =  new ArrayList<Map<String, Object>>();
    
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.searchsite);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        Log.d(TAG, "[onCreate...] ");
        
        this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
        
        Button btnSearch = (Button)this.findViewById(R.id.btnSearch);
        btnSearch.setOnClickListener(new SearchButtonListener());
        
        tvKeyword = (AutoCompleteTextView)findViewById(R.id.actvKeyword);
    	tvKeyword.addTextChangedListener(new KeywordTextWatcher());
    	
        view= (View)findViewById(R.id.entire_view_searchsite);
        view.setOnTouchListener(new TouchItemClickListener());
    }
    
	public void onResume() {
		super.onResume();	
		Log.d(TAG, "[onResume...] ");	
	}
	
	class TouchItemClickListener implements OnTouchListener
    {
		public boolean onTouch(View v, MotionEvent event) {
			Log.d(TAG, "[onTouch...] ");	
			hideSoftKeyboard();
        	
			return true;
		}		
    }
	
	private void hideSoftKeyboard(){
		tvKeyword.clearFocus();
    	InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
    	imm.hideSoftInputFromWindow(tvKeyword.getWindowToken(), 0);
	}
	
	class KeywordTextWatcher implements TextWatcher
	{
		public void afterTextChanged(Editable s)
		{
			AutoCompleteTextView tvKeyword = (AutoCompleteTextView)findViewById(R.id.actvKeyword);
			String keyword = tvKeyword.getText().toString().trim();
			if (keyword.length() == 2)
			{
				ArrayAdapter<String> adapter = new ArrayAdapter<String>(SearchSite.this, 
																		R.layout.autocompleteitem, 
																		getAutoCompleteData(keyword));
		    	tvKeyword.setAdapter(adapter);
			}
		}
		
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // noop
        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            // noop
        }

	}
	
	private String[] getAutoCompleteData(String keyword) {	
		String databaseFilename = TabBarFramework.DATABASE_PATH + "/" + TabBarFramework.DATABASE_FILENAME;
		SQLiteDatabase db;
		String strWebsite = "";
		boolean ifNotFirst = false;

		db = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);
		Cursor result=db.rawQuery("SELECT VG_ENGLISH FROM VG_WebSites where VG_ENGLISH like '" + keyword + "%'", null); 
		if (result.moveToFirst())
		{
			while (!result.isAfterLast()) {
				String siteName = result.getString(0).trim();
				
				if(ifNotFirst)
				{
					strWebsite += ",";
				}
				strWebsite += siteName;
				ifNotFirst = true;
				
				result.moveToNext(); 
			}
		}
		result.close(); 
		db.close();
		
		return strWebsite.split(",");
	}
    
    class SearchButtonListener implements OnClickListener
    {
    	public void onClick(View v)
    	{
    		AutoCompleteTextView actvKeyword = (AutoCompleteTextView)findViewById(R.id.actvKeyword);
        	String keyword = actvKeyword.getText().toString().trim();
        	        	
    		getSearchResult(keyword);
    	}
    }
    
    private void getSearchResult(String keyword)
    {
    	if (!keyword.equals(""))
    	{
    		getSearchResultData(keyword);
    	}
		
		TextView tvRecordCount = (TextView)findViewById(R.id.tvRecordCount);
		tvRecordCount.setText(resultList.size() + " results");
		
    	ListView lvSearchResult = (ListView)findViewById(R.id.lvSearchResult);
//		SimpleAdapter adapter = new SimpleAdapter(this,resultList,R.layout.searchresultitem,
//			new String[]{"siteName"},
//			new int[]{R.id.tvSiteName});
//    	lvSearchResult.setAdapter(adapter);
		lvSearchResult.setAdapter(new EvaluationAdapter());
    	lvSearchResult.setOnItemClickListener(new ItemClickListener());
    } 
    
    class EvaluationAdapter extends ArrayAdapter<String> {
		public EvaluationAdapter() {
			super(SearchSite.this, R.layout.searchresultitem, new String[resultList.size()]);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			if (position + 1 > resultList.size())
				return null;

			Map<String, Object> map = resultList.get(position);
			LayoutInflater inflater = getLayoutInflater();
			View row = inflater.inflate(R.layout.searchresultitem, parent, false);
			TextView textView = (TextView) row.findViewById(R.id.tvSiteName);
			textView.setText(Html.fromHtml(map.get("siteName").toString()));

//			Log.d(TAG,"[EvaluationAdapter.sitename( "+ map.get("siteName").toString() + ")]");
			
			return row;
		}
	}
    
	private void getSearchResultData(String keyword) {
		resultList.clear();
		
		String databaseFilename = TabBarFramework.DATABASE_PATH + "/" + TabBarFramework.DATABASE_FILENAME;
		SQLiteDatabase db;

		db = SQLiteDatabase.openOrCreateDatabase(databaseFilename, null);
		Cursor result=db.rawQuery("SELECT VG_ID, VG_ENGLISH, VG_HTTPURL FROM VG_WebSites where VG_ENGLISH like '%" + keyword + "%'", null); 
		if (result.moveToFirst())
		{
			while (!result.isAfterLast()) {
				String siteID = result.getString(0);
				String siteName = result.getString(1);
				
				//highlight the keyword
				Matcher m = Pattern.compile(keyword, Pattern.CASE_INSENSITIVE).matcher(siteName);
				StringBuffer stringBuffer = new StringBuffer();
				int lastIndex=0;
				while (m.find()) {
	    			int start = m.start();
	    			int end = m.end();	 
	    			if(lastIndex<start)stringBuffer.append(siteName.substring(lastIndex,start));
	    			lastIndex =end;
	    			String stringMarch=siteName.substring(start,end);
	    			stringBuffer.append("<font color='red'>"+stringMarch+"</font>");
	    		}	
				if(lastIndex<siteName.length()){
					stringBuffer.append(siteName.substring(lastIndex,siteName.length()));
				}				
				
				String siteUrl = result.getString(2);
				Map<String, Object> map = new HashMap<String, Object>();
				map.put("siteName", stringBuffer.toString());
				map.put("siteUrl", siteUrl);
				map.put("siteID", siteID);
				resultList.add(map);
				result.moveToNext(); 
			}
		}
		result.close(); 
		db.close();
	}
    
	class  ItemClickListener implements OnItemClickListener     
	{     
		public void onItemClick(AdapterView<?> arg0,//The AdapterView where the click happened      
				View arg1,//The view within the AdapterView that was clicked     
				int arg2,//The position of the view in the adapter     
				long arg3//The row id of the item that was clicked     
		) {      
//			HashMap<String, Object> item=(HashMap<String, Object>) arg0.getItemAtPosition(arg2);
			Map<String, Object> map= resultList.get(arg2);
			hideSoftKeyboard();
//			openUrl((String)item.get("siteUrl"));
			openUrl((String)map.get("siteUrl"));
		}	
	}
	
	private void openUrl(String url) {
		Uri uri = Uri.parse(url);
		Intent intent = new Intent(Intent.ACTION_VIEW, uri);
		startActivity(intent); 
	}
	
}